package com.tianji.learning.task;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayTask<D> implements Delayed {

    // 任务数据
    private D data;

    // 执行时间(纳秒)
    private long activeTime;

    public DelayTask(D data, Duration delayTime) {
        this.data = data;
        this.activeTime = System.nanoTime() + delayTime.toNanos();
    }

    /**
     * 执行时间 - 当前时间 = 剩余时间
     * 返回任务执行 剩余的时间
     *
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(0, activeTime - System.nanoTime()), TimeUnit.NANOSECONDS);
    }

    /**
     * 排序
     *
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long time = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (time > 0) {
            return 1;
        } else if (time < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}
